<?php

namespace app\admin\model;

use app\common\model\CarRepertoryCalendar;
use think\Exception;
use think\Model;


class RentalOrder extends Model
{





    // 表名
    protected $name = 'rental_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];



    public function getStatusList()
    {
        return ['ordering' => __('Status ordering'), 'renting' => __('Status renting'), 'complete' => __('Status complete'), 'cancel' => __('Status cancel')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 减少车辆库存
     * @param $carId
     * @param $startDate
     * @param $endDate
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws Exception
     */
    public function reduceCarRepertory($carId, $startDate, $endDate)
    {
        $cars = new Cars();
        $carRepertoryCalendar = new CarRepertoryCalendar();
        // 得到车辆设置的总库存
        $totalInventory = $cars->value('total_inventory');

        // 库存日历表中的剩余库存
        $where = "car_id = $carId and date(calendar) >= '$startDate' and date(calendar) <= '$endDate'";
        $calendar = $carRepertoryCalendar->field("id,car_id,calendar,remain_repertory")
            ->where($where)->select();

        $c_arr = [];
        foreach ($calendar as $k => $c) {
            if( $c->remain_repertory===0){
                $msg = "车id{$c->car_id}在{$c->calendar中}剩余库存为0";
                throw new Exception($msg);
            }
            $c_arr[$c->calendar]['id'] = $c->id;
            $c_arr[$c->calendar]['car_id'] = $c->car_id;
            $c_arr[$c->calendar]['remain_repertory'] = $c->remain_repertory;
        }

        //计算两个日期之间的相差的天数
        $days = $this->getIntervalDay($startDate, $endDate);
        // 组装要更新的库存日历的数据
        $data = [];
        for ($i = 0; $i < $days; $i++) {
            $str = "+$i day";
            $insetDate = date("Y-m-d", strtotime($str, strtotime($startDate)));
            if (array_key_exists($insetDate, $c_arr)) {
                $remain = $c_arr[$insetDate]['remain_repertory'] - 1;
                $id = $c_arr[$insetDate]['id'];
                $data[] = ['id' => $id, 'car_id' => $carId, 'calendar' => $insetDate, 'remain_repertory' => $remain];
            }else{
                $data[] = ['car_id' => $carId, 'calendar' => $insetDate, 'remain_repertory' => $totalInventory - 1];
            }
        }

        $saveAll = $carRepertoryCalendar->saveAll($data);
        if (!$saveAll)
            return true;
        return false;
    }

    /**
     * 增加库存
     * @param $carId
     * @param $startDate
     * @param $endDate
     * @return bool
     * @throws Exception
     */
    public function addCarRepertory($carId, $startDate, $endDate){
        $cars = new Cars();
        $carRepertoryCalendar = new CarRepertoryCalendar();
        // 得到车辆设置的总库存
        $totalInventory = $cars->value('total_inventory');

        // 库存日历表中的剩余库存
        $where = "car_id = $carId and date(calendar) >= '$startDate' and date(calendar) <= '$endDate'";
        $calendar = $carRepertoryCalendar->field("id,car_id,calendar,remain_repertory")
            ->where($where)->select();

        $c_arr = [];
        foreach ($calendar as $k => $c) {
            if( $c->remain_repertory>=$totalInventory){
                $msg = "车id{$c->car_id}在{$c->calendar中}剩余库存为总库存";
                throw new Exception($msg);
            }
            $c_arr[$c->calendar]['id'] = $c->id;
            $c_arr[$c->calendar]['car_id'] = $c->car_id;
            $c_arr[$c->calendar]['remain_repertory'] = $c->remain_repertory;
        }

        //计算两个日期之间的相差的天数
        $days = $this->getIntervalDay($startDate, $endDate);
        // 组装要更新的库存日历的数据
        $data = [];
        for ($i = 0; $i < $days; $i++) {
            $str = "+$i day";
            $insetDate = date("Y-m-d", strtotime($str, strtotime($startDate)));
            if (array_key_exists($insetDate, $c_arr)) {
                $remain = $c_arr[$insetDate]['remain_repertory'] + 1;
                $id = $c_arr[$insetDate]['id'];
                $data[] = ['id' => $id, 'car_id' => $carId, 'calendar' => $insetDate, 'remain_repertory' => $remain];
            }else{
                $data[] = ['car_id' => $carId, 'calendar' => $insetDate, 'remain_repertory' => $totalInventory + 1];
            }
        }
        $saveAll = $carRepertoryCalendar->saveAll($data);
        if (!$saveAll)
            return true;
        return false;
    }

    /**
     * 获得两个时间间隔的天数
     * @param $startDate
     * @param $endDate
     * @return float|int
     */
    public function getIntervalDay($startDate, $endDate)
    {
        $date1 = strtotime($startDate);
        $date2 = strtotime($endDate);
        //计算两个日期之间的相差的天数
        $diff = $date1 - $date2 ;
        return abs(round($diff / 86400)) + 1;
    }


}
